namespace SimpleWebServices.Net
{
    using System;
    using System.IO;
    using System.Net;
    using System.Text;
    using HtmlAgilityPack;

    public sealed class HtmlResponse : Response
    {
        private HtmlDocument _html;

        public HtmlResponse(HttpWebResponse response)
            : base(response.StatusCode, response.ResponseUri, response.Headers, response.Cookies)
        {
            HtmlDocument html = null;
            using (Stream stream = response.GetResponseStream())
            {
                html = new HtmlDocument();
                using (StreamReader reader = new StreamReader(stream))
                {
                    html.LoadHtml(reader.ReadToEnd());
                }
            }

            this.Html = html;
        }

        public HtmlDocument Html
        {
            get
            {
                return this._html;
            }

            private set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }

                this._html = value;
            }
        }

        public static HtmlResponse New(HttpRequestDefinition definition, IHttpContent content)
        {
            HtmlResponse result = null;

            using (HttpWebResponse response = Response.Http(definition, content) as HttpWebResponse)
            {
                result = new HtmlResponse(response);
            }

            return result;
        }

        public override string ToString()
        {
            StringBuilder buffer = new StringBuilder();
            buffer.Append(base.ToString());
            buffer.Append(Environment.NewLine);
            buffer.Append(this.Html.DocumentNode.OuterHtml);

            return buffer.ToString();
        }
    }
}